const crypto = require('crypto');
const wxApisConfig = require('../../config/wxapi.json');

/**
 * 排序
 * @param arrays
 * @return {{}}
 */
function objKeySort (arrays) {
    let newkey = Object.keys(arrays).sort();
    let newObj = {};
    for (let i = 0; i < newkey.length; i++) {
        newObj[newkey[i]] = arrays[newkey[i]];
    }
    return newObj;
}

/**
 * Sha256加密
 * @param data
 * @return {string}
 */
function calcHmacSha256 (data) {
    let hmac = crypto.createHmac('sha256', wxApisConfig.payment.mchAPISecret);
    let up = hmac.update(data);
    return up.digest('hex').toUpperCase();
}

/**
 * @Description 计算MD5
 * @author 53010
 * @date 2020-10-30 11:48
 */
function calcMD5 (data) {
    return crypto.createHash('md5').update(data).digest('hex').toString().toLocaleUpperCase();
}

/**
 * 将字典转换成字符串
 * @param dict
 * @return {string}
 */
function convertDictToString (dict) {
    dict.key = wxApisConfig.payment.mchAPISecret;
    let lastString = '';
    for (let key in dict) {
        if (dict[key]) {
            lastString += key + '=' + dict[key] + '&';
        }
    }
    return lastString.substr(0, lastString.length - 1);
}

/**
 * 生成支付签名
 * @param signData
 * @returns {string}
 */
function generatePaySign (signData) {
    signData.appId = wxApisConfig.secret.appId;
    // 过滤空值参数
    for (let key in signData) {
        if (signData[key] && signData[key] === '') {
            delete signData[key];
        }
    }
    // 排序
    signData = objKeySort(signData);
    // 转换序列化字符串
    let signDataSerial = convertDictToString(signData);
    // console.log(signDataSerial);
    return calcHmacSha256(signDataSerial);
}

/**
 * 生成订单签名
 * @param signData
 * @param useMd5
 * @return {string}
 */
function generateOrderSign (signData, useMd5) {
    // 过滤空值参数
    for (let key in signData) {
        if (signData[key] && signData[key] === '') {
            delete signData[key];
        }
    }
    // 排序
    signData = objKeySort(signData);
    // 转换序列化字符串
    let signDataSerial = convertDictToString(signData);
    if (useMd5) {
        return calcMD5(signDataSerial);
    } else {
        return calcHmacSha256(signDataSerial);
    }
}

module.exports = {
    generatePaySign,
    generateOrderSign
};
